package com.xinda.admin.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import com.xinda.admin.service.AdminService;

@Controller
public class LoginController {
	
	private String adminName;
	@Resource
	private AdminService adminService;
	
	@RequestMapping(value = "loginPage")
	public String loginPage() {
		
            return "admin/login" ;
	}
	
	@RequestMapping(value = "login")
	public String login(@RequestParam(value="txt_kensyo")String input, HttpSession kaptchasession, String username,String password,Model model,HttpServletRequest request) {
		
		String kaptchaExpected = (String) kaptchasession.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		
		
		if(!kaptchaExpected.equals(input)){
			model.addAttribute("message","验证码错误") ;
            return "admin/login" ;
		}
		
		Subject subject = SecurityUtils.getSubject() ;
		
        UsernamePasswordToken token = new UsernamePasswordToken(username,password) ;
        try {
            subject.login(token);
            
            
            adminName = username;
            Integer adminRoleId =adminService.selectAdminRoleByName(username);
            Session session = subject.getSession();
            session.setAttribute("username", username);
            session.setAttribute("adminRoleId", adminRoleId);
            session.setAttribute("isLogin",1);
            return "admin/index" ;
        }catch (Exception e){
            //这里将异常打印关闭是因为如果登录失败的话会自动抛异常
        	//e.printStackTrace();
        	model.addAttribute("message","用户名或密码错误") ;
            return "admin/login" ;
        }

	}
	
	
	@RequestMapping(value = "logout")
	public String logout(HttpSession session,HttpServletRequest request) {
		
		Date date = new Date();
        String ip = request.getRemoteAddr();
        adminService.setLastLogin(adminName,date,ip);
		session.removeAttribute("username");
		session.removeAttribute("adminRoleId");
        return "admin/login";
    }

	

}
